<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace App\Model\LazyCommon;
use App\Base\BaseModel;
use BaseExt\MyCurl;
use App\Entity\WechatCode;

class WechatCodeModel extends BaseModel{

    /**
     * @return \Doctrine\ORM\EntityRepository
     */
    public function getRep()
    {
        return $this->em->getRepository("App:WechatCode");
    }

    /**
     * @param $openid
     * @return null|object|WechatCode
     */
    public function getByOpenid($openid)
    {
        return $this->getRep()->findOneBy(array("openid"=>$openid));
    }

    /**
     * @param $phone
     * @return null|object|WechatCode
     */
    public function getByPhone($phone)
    {
        return $this->getRep()->findOneBy(array("phone"=>$phone));
    }

    /**
     * @param $phone
     * @param $openid
     * @return bool
     */
    public function bindUser($phone,$openid)
    {
        if ($this->getByPhone($phone)) {
            //手机号被占用
            return false;
        } else {
            $WechatCode = new WechatCode();
            $WechatCode->setAddtime(0)
                ->setCode(0)
                ->setOpenid($openid)
                ->setPhone($phone);
            $this->em->persist($WechatCode);
            $this->em->flush();
            return true;
        }
    }


    /**
     * @param $openid
     * @return bool|WechatCode|null
     */
    public function createCode($openid)
    {
        $WechatCode = $this->getByOpenid($openid);
        if (!$WechatCode) {
            //没有找到绑定关系无法创建验证码
            return false;
        } else {
            //找到对应关系，创建验证码
            $code = rand(1000,9999);
            $WechatCode->setCode($code)
                ->setAddtime(time());
            return $WechatCode;
        }
    }

    public function checkCode($phone,$code)
    {
        $WechatCode = $this->getByPhone($phone);
        if (!$WechatCode || $WechatCode->getCode() != $code) {
            return false;
        } else {
            //检查验证码的有效时间
            if ($WechatCode->getAddtime() < time() - 900) {
                return false;
            } else {
                return true;
            }
        }
    }


}